package com.weirdor.boot.admin.www.common;

import com.weirdor.boot.common.utils.QiniuUtil;
import com.weirdor.boot.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class UploadController {

    @Autowired
    private ServletContext app;


    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Map<String,Object> upload(HttpServletRequest request, MultipartFile file) throws IOException {
        Map<String,Object> map=new HashMap<>();
        //如果文件不为空，写入上传路径
        if(!file.isEmpty()) {
            //上传文件路径
            String contextPath = app.getRealPath("upload");


            //上传文件名
            String filename = file.getOriginalFilename();
            //获取上传文件的后缀名
            String prefix=filename.substring(filename.lastIndexOf(".")+1);
            //通过uuid来设置文件名
            filename= UUID.randomUUID()+"."+prefix;
            File filepath = new File(contextPath,filename);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(contextPath + File.separator + filename));
            map.put("code",0);
            map.put("src","/"+UUID.randomUUID()+"."+prefix);
        } else {
            map.put("code",1);
        }
        return  map;
    }

}
